package com.zyx.controller;

import com.github.pagehelper.PageInfo;
import com.zyx.pojo.*;
import com.zyx.service.*;
import com.zyx.vo.GetSession;
import com.zyx.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("Admin")
public class AdminController {
    @Resource
    private AutoService autoService;
    @Resource
    private UserService userService;
    @Resource
    private SpencerService spencerService;
    @Resource
    private OrderService orderService;
    @Autowired
    private RelevancyService relevancyService;
    @Autowired
    private NameService nameService;


    //如果实体类的日期类型需要从页面获取数据，那么避免NULL转换为日期类型出问题
    //解决方法1：@InitBinder
    //解决方法2：在实体类的日期类型属性上添加注解@DateTimeFormat(pattern = "yyyy-MM-dd")
    @InitBinder
    protected void initDateFormatBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    //每日汽车数据
    @ResponseBody
    @RequestMapping(value = "AutoSize", method = RequestMethod.GET)
    public Map<String, Integer> queryAllAuto() {
        Map<String, Integer> map = new HashMap<>();
        map = autoService.queryAllCar();
        return map;
    }

    //每日用户数据
    @ResponseBody
    @RequestMapping(value = "UserSize", method = RequestMethod.GET)
    public Map<String, Integer> queryAllUser() {

        Map<String, Integer> map = new HashMap<>();
        map = userService.queryAll();
        return map;
    }


    //每日4S店数据
    @ResponseBody
    @RequestMapping(value = "SpencerSize", method = RequestMethod.GET)
    public Map<String, Integer> queryAllSpencer(HttpServletRequest req) {
        Map<String, Integer> map = new HashMap<>();
        map = spencerService.queryAll();
        return map;
    }

    //每日看车数据
    @ResponseBody
    @RequestMapping(value = "OrderSize", method = RequestMethod.GET)
    public Map<String, Integer> queryAllOrder() {

        Map<String, Integer> map = new HashMap<>();
        map = orderService.queryAll();
        return map;
    }

    //车辆信息分页查询
    @ResponseBody
    @RequestMapping(value = "listAuto", method = RequestMethod.POST)
    public ResultVo<Auto> queryByPage(Integer pageNum, Integer pageSize, Auto auto) {
        if (auto != null) {
            System.out.println("auto:" + auto);
        }
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 5;
        }
        PageInfo<Auto> teamPageInfo = autoService.queryAll(pageNum, pageSize, auto);//调用分页查询和模糊查询
        return new ResultVo<>(teamPageInfo);
    }

    //店铺信息分页查询
    @ResponseBody
    @RequestMapping(value = "listSpencer", method = RequestMethod.POST)
    public ResultVo<Spencer> queryByPage(Integer pageNum, Integer pageSize, Spencer spencer) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 5;
        }
        PageInfo<Spencer> teamPageInfo = spencerService.queryAll(pageNum, pageSize, spencer);//调用分页查询和模糊查询
        return new ResultVo<>(teamPageInfo);
    }

    //用户信息分页查询
    @ResponseBody
    @RequestMapping(value = "listUser", method = RequestMethod.POST)
    public ResultVo<User> queryByPage(Integer pageNum, Integer pageSize, User user) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 5;
        }
        PageInfo<User> teamPageInfo = userService.queryAll(pageNum, pageSize, user);//调用分页查询和模糊查询
        return new ResultVo<>(teamPageInfo);
    }

    //预约人信息分页查询
    @ResponseBody
    @RequestMapping(value = "listOrders", method = RequestMethod.POST)
    public ResultVo<Orders> queryByPage(Integer pageNum, Integer pageSize, Orders orders) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 5;
        }
        System.out.println(orders.getUserName());
        PageInfo<Orders> teamPageInfo = orderService.queryAll(pageNum, pageSize, orders);//调用分页查询和模糊查询
        return new ResultVo<>(teamPageInfo);
    }

    //添加车辆信息
    @ResponseBody
    @RequestMapping(value = "addAuto", method = RequestMethod.POST)
    public ResultVo<Auto> addAuto(Auto auto) {
        auto.setTimeMarket(new Date());
        int i = autoService.addAuto(auto);
        if (i == 1) {
            return new ResultVo<>();
        }
        return new ResultVo<>(500, "添加失败！稍后再试！");
    }

    //添加店铺信息
    @ResponseBody
    @RequestMapping(value = "addSpencer", method = RequestMethod.POST)
    public ResultVo<Spencer> addSpencer(Spencer spencer) {
        spencer.setCreateTime(new Date());
        int i = spencerService.addSpencer(spencer);
        if (i == 1) {
            return new ResultVo<>();
        }
        return new ResultVo<>(500, "添加失败！稍后再试！");
    }

    //根据商铺id获取店铺名称
    @ResponseBody
    @RequestMapping(value = "selectByName", method = RequestMethod.POST)
    public List<Relevancy> selectByName() {
        List<Relevancy> list = relevancyService.selectByName();
        return list;
    }

    /**
     * 根据商铺Id获取店铺所有类型车辆
     *
     * @param i
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectByAuto", method = RequestMethod.GET)
    public List<Relevancy> selectByAuto(int i) {
        List<Relevancy> list = relevancyService.selectByAutoName(i);
        return list;
    }

    /**
     * 添加预约信息
     * @param orders
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addOrder", method = RequestMethod.POST)
    public ResultVo<Orders> addOrder(Orders orders) {
        orders.setState(0);
        int i = orderService.addOrder(orders);
        if (i == 1) {
            return new ResultVo<>();
        }
        return new ResultVo<>(500, "添加失败！稍后再试！");
    }

    //添加用户信息
    @ResponseBody
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public ResultVo<User> addUser(User user) {
        user.setState(0);
        user.setCreateTime(new Date());
        int i = userService.addUser(user);
        if (i == 1) {
            return new ResultVo<>();
        } else if (i == -1) {
            return new ResultVo<>(500, "手机号已经注册过");
        }
        return new ResultVo<>(500, "添加失败！稍后再试！");
    }

    //根据主键查询车辆信息
    @ResponseBody
    @RequestMapping(value = "selectKey", method = RequestMethod.GET)
    public Auto selectKey(int id) {
        Auto auto = autoService.selectByKey(id);
        return auto;
    }

    //根据主键更新车辆信息
    @ResponseBody
    @RequestMapping(value = "autoUpdate/{id}", method = RequestMethod.PUT)
    public ResultVo<Auto> updateAuto(@PathVariable("id") Integer autoId, Auto auto) {
        auto.setAutoId(autoId);
        int i = autoService.updateAuto(auto);
        if (i == 1) {
            return new ResultVo<Auto>();
        }
        return new ResultVo<>(500, "添加失败！请稍后再试！");
    }

    //根据主键删除车辆信息
    @ResponseBody
    @RequestMapping(value = "autoDel/{id}", method = RequestMethod.DELETE)
    public ResultVo<Auto> deleteAuto(@PathVariable("id") Integer autoId, Auto auto) {
        auto = autoService.selectByKey(autoId);
        int i = autoService.deleteAuto(auto);
        if (i == 1) {
            return new ResultVo<Auto>();
        }
        return new ResultVo<>(500, "删除失败！请稍后再试！");
    }

    //根据主键查询店铺信息
    @ResponseBody
    @RequestMapping(value = "selectKeySpencer", method = RequestMethod.GET)
    public Spencer selectKeySpencer(int id) {
        Spencer spencer = spencerService.selectByKey(id);
        return spencer;
    }

    //根据主键更新店铺信息
    @ResponseBody
    @RequestMapping(value = "spencer/{id}", method = RequestMethod.PUT)
    public ResultVo<Spencer> updateSpencer(@PathVariable("id") Integer autoId, Spencer spencer) {
        spencer.setSpencerId(autoId);
        int i = spencerService.updateSpencer(spencer);
        if (i == 1) {
            return new ResultVo<Spencer>();
        }
        return new ResultVo<>(500, "添加失败！请稍后再试！");
    }

    //根据主键删除店铺信息
    @ResponseBody
    @RequestMapping(value = "spencer/{id}", method = RequestMethod.DELETE)
    public ResultVo<Spencer> deleteSpencer(@PathVariable("id") Integer autoId, Spencer spencer) {
        spencer = spencerService.selectByKey(autoId);
        int i = spencerService.deleteAuto(spencer);
        if (i == 1) {
            return new ResultVo<Spencer>();
        }
        return new ResultVo<>(500, "删除失败！请稍后再试！");
    }

    //根据主键查询用户信息
    @ResponseBody
    @RequestMapping(value = "selectKeyUser", method = RequestMethod.GET)
    public User selectKeyUser(int id) {
        User user = userService.selectByKeyUser(id);
        return user;
    }

    //根据主键更新用户信息
    @ResponseBody
    @RequestMapping(value = "userAdd/{id}", method = RequestMethod.PUT)
    public ResultVo<User> updateUser(@PathVariable("id") Integer autoId, User user) {
        user.setUserId(autoId);
        int i = userService.updateUser(user);
        if (i == 1) {
            return new ResultVo<User>();
        }
        return new ResultVo<>(500, "添加失败！请稍后再试！");
    }

    //根据主键删除用户信息
    @ResponseBody
    @RequestMapping(value = "userDelete/{id}", method = RequestMethod.DELETE)
    public ResultVo<User> deleteUser(@PathVariable("id") Integer autoId, User user) {
        user = userService.selectByKeyUser(autoId);
        int i = userService.deleteUser(user);
        if (i == 1) {
            return new ResultVo<User>();
        }
        return new ResultVo<>(500, "删除失败！请稍后再试！");
    }

    //添加新的车型或者是新的品牌
    @ResponseBody
    @RequestMapping(value = "addAutoName",method = RequestMethod.POST)
    public ResultVo addAutoName(Name name){
        int i = nameService.addAutoName(name);
        if (i>0){
            return new ResultVo();
        } else if (i == -1) {
            return new ResultVo(500,"此汽车型号已有，可以进行添加");
        }
        return new ResultVo(500,"添加失败");
    }

    @ResponseBody
    @RequestMapping(value = "user", method = RequestMethod.POST)
    public Admin querySpencer(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        GetSession getSession = new GetSession();
        Admin admin = getSession.adminSession(request, response, session);
        return admin;
    }

    //查询所有店铺车辆和店铺名称
    @ResponseBody
    @RequestMapping(value = "queryAll", method = RequestMethod.GET)
    public ResultVo<Relevancy> queryAll(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 5;
        }
        PageInfo<Relevancy> relevancyPageInfo = relevancyService.queryAll(pageNum, pageSize);
        return new ResultVo<>(relevancyPageInfo);
    }

    //上传汽车图片并更新图片信息
    @ResponseBody
    @RequestMapping(value = "autoLogo/{id}", method = RequestMethod.POST)
    public ResultVo uploadLogo(@RequestParam("logo") MultipartFile myFile, HttpServletRequest request, @PathVariable("id") Integer id) {
        //文件上传到指定服务器位置
        String path = request.getServletContext().getRealPath("/assets/images/auto/");
        //获取文件名称
        String originalFilename = myFile.getOriginalFilename();
        //定义新的文件名称：随机生成名称+文件后缀名
        String randomName = UUID.randomUUID().toString().replace("-", "");
        int i = originalFilename.lastIndexOf(".");
        String hz = originalFilename.substring(i);
        String logoName = randomName + hz;
        int num = 0;
        try {
            myFile.transferTo(new File(path + "/" + logoName));
            System.out.println("上传成功！" + path + logoName);
            Auto auto = new Auto();
            auto.setAutoId(id);
            auto.setPicture(logoName);
            Auto a = autoService.selectByKey(id);
            //将图片名称更新到数据库中
            num = autoService.updateAuto(auto);
            //将原有图片删除
            if (a.getPicture() != null) {
                File file = new File("D:\\Text\\cat\\target\\cat-1.0-SNAPSHOT\\assets\\images\\auto\\" + a.getPicture());
                file.delete();
            }
            if (num == 1) {
                return new ResultVo();
            } else {
                return new ResultVo(500, "上传失败！请稍后再试！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVo(500, "图片上传失败！" + e.getMessage());
        }

    }

    //上传店铺图片并更新图片信息
    @ResponseBody
    @RequestMapping(value = "spencerLogo/{id}")
    public ResultVo<Spencer> upSpencerLogo(@RequestParam("logo") MultipartFile myFile, HttpServletRequest request, @PathVariable("id") Integer id) {
        //文件上传到指定服务器位置
        String path = request.getServletContext().getRealPath("/assets/images/spencer/");
        //获取文件名称
        String originalFilename = myFile.getOriginalFilename();
        //定义新的文件名称：随机生成名称+文件后缀名
        String randomName = UUID.randomUUID().toString().replace("-", "");
        int i = originalFilename.lastIndexOf(".");
        String hz = originalFilename.substring(i);
        String logoName = randomName + hz;
        int num = 0;
        try {
            myFile.transferTo(new File(path + "/" + logoName));
            System.out.println("上传成功！" + path + "/" + logoName);
            Spencer spencer = new Spencer();
            spencer.setSpencerId(id);
            spencer.setPicture(logoName);
            Spencer s = spencerService.selectByKey(id);
            //将图片名称更新到数据库中
            num = spencerService.updateSpencer(spencer);
            //将原有图片删除
            if (s.getPicture() != null) {
                File file = new File("D:\\Text\\cat\\target\\cat-1.0-SNAPSHOT\\assets\\images\\spencer\\" + s.getPicture());
                file.delete();
            }
            if (num == 1) {
                return new ResultVo<Spencer>();
            } else {
                return new ResultVo<>(500, "上传失败！请稍后再试！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVo<>(500, "图片上传失败！" + e.getMessage());
        }

    }

    //新增车型详细图
    @ResponseBody
    @RequestMapping(value = "autoPicture/{id}")
    public ResultVo autoPicture(@RequestParam("auto") MultipartFile[] myFiles, HttpServletRequest request, @PathVariable("id") Integer id) {
        //文件上传到指定服务器位置
        String path = request.getServletContext().getRealPath("/assets/images/auto/" + id);
        File f = new File(path);
        if (!f.exists()) {
            f.mkdir();
        }
        //获取文件名称
        int i = autoService.queryPicture(id);
        try {
            for (MultipartFile myFile : myFiles) {
                String originalFilename = myFile.getOriginalFilename();
                //定义新的文件名称：随机生成名称+文件后缀名
                int index = originalFilename.lastIndexOf(".");
                String hz = originalFilename.substring(index);
                String logoName = i++ + ".jpg";
                myFile.transferTo(new File(path + "\\" + logoName));
                System.out.println("上传成功！" + path + "\\" + logoName);
                System.out.println(i);
            }
            Auto auto = new Auto();
            auto.setAutoId(id);
            auto.setUtilityTime(i);
            int a = autoService.updateAuto(auto);
            if (a > 0) {
                return new ResultVo();
            } else {
                return new ResultVo(500, "上传失败！请稍后再试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVo(500, "图片上传失败！" + e.getMessage());
        }
    }

    //查询车型图片
    @ResponseBody
    @RequestMapping(value = "autoPicture",method = RequestMethod.GET)
    public List<String> autoPicture(Integer id){
        int i = autoService.queryPicture(id);
        String path = "D:/Text/cat/target/cat-1.0-SNAPSHOT/assets/images/auto/" + id;
        List<String> list = new ArrayList<>();
        for (int a = 0;a<i;a++){
            list.add(path+"\\"+a+".jpg");
        }
        return list;
    }

    //根据id获取车型信息
    @ResponseBody
    @RequestMapping(value = "queryName",method = RequestMethod.GET)
    public Name queryName(Integer id){
        return nameService.queryName(id);
    }

    //上传店铺图片并更新图片信息
    @ResponseBody
    @RequestMapping(value = "carNameLogo/{id}")
    public ResultVo<Spencer> carNameLogo(@RequestParam("logo") MultipartFile myFile, HttpServletRequest request, @PathVariable("id") Integer id) {
        //文件上传到指定服务器位置
        String path = request.getServletContext().getRealPath("/assets/images/carName");
        //获取文件名称
        String originalFilename = myFile.getOriginalFilename();
        //定义新的文件名称：随机生成名称+文件后缀名
        String randomName = UUID.randomUUID().toString().replace("-", "");
        int i = originalFilename.lastIndexOf(".");
        String hz = originalFilename.substring(i);
        String logoName = randomName + hz;
        int num = 0;
        try {
            myFile.transferTo(new File(path + "/" + logoName));
            System.out.println("上传成功！" + path + "/" + logoName);
            Name name = nameService.queryName(id);
            Name n = new Name();
            n.setId(id);
            n.setPicture(logoName);
            //将图片名称更新到数据库中
            num = nameService.carNameLogo(n);
            //将原有图片删除
            if (n.getPicture() != null) {
                File file = new File("D:\\Text\\cat\\target\\cat-1.0-SNAPSHOT\\assets\\images\\carNameLogo\\" + n.getPicture());
                file.delete();
            }
            if (num == 1) {
                return new ResultVo<Spencer>();
            } else {
                return new ResultVo<>(500, "上传失败！请稍后再试！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVo<>(500, "图片上传失败！" + e.getMessage());
        }

    }
}
